import { STORAGE_KEYS, DATA_VERSION } from '@/constants/storage';
import { storageService } from '@/services/storage';
import { studentService } from '@/services/student';
import { courseService, courseCategoryService } from '@/services/course';
import { scheduleService } from '@/services/schedule';
import type { OperationResult } from '@/types/common/base';
import type { IStudent } from '@/types/student/student';
import type { ICourse } from '@/types/course/course';
import type { ICourseCategory } from '@/types/course/courseCategory';
import type { IScheduleTemplate } from '@/types/schedule/scheduleTemplate';
import type { IScheduleInstance } from '@/types/schedule/scheduleInstance';

/**
 * 导出数据格式接口
 */
export interface IExportData {
  /** 数据版本 */
  version: string;
  /** 导出时间戳 */
  timestamp: number;
  /** 导出描述 */
  description?: string;
  /** 数据内容 */
  data: {
    /** 学生数据 */
    students: IStudent[];
    /** 课程数据 */
    courses: ICourse[];
    /** 课程分类数据 */
    courseCategories: ICourseCategory[];
    /** 课程安排模板数据 */
    scheduleTemplates: IScheduleTemplate[];
    /** 课程实例数据 */
    scheduleInstances: IScheduleInstance[];
    /** 应用设置 */
    appSettings?: Record<string, unknown>;
    /** 用户偏好设置 */
    userPreferences?: Record<string, unknown>;
  };
  /** 统计信息 */
  statistics: {
    /** 学生数量 */
    studentCount: number;
    /** 课程数量 */
    courseCount: number;
    /** 分类数量 */
    categoryCount: number;
    /** 模板数量 */
    templateCount: number;
    /** 实例数量 */
    instanceCount: number;
  };
}

/**
 * 导入结果接口
 */
export interface IImportResult {
  /** 是否成功 */
  success: boolean;
  /** 导入的数据统计 */
  imported: {
    /** 学生数量 */
    studentCount: number;
    /** 课程数量 */
    courseCount: number;
    /** 分类数量 */
    categoryCount: number;
    /** 模板数量 */
    templateCount: number;
    /** 实例数量 */
    instanceCount: number;
  };
  /** 跳过的数据统计 */
  skipped: {
    /** 学生数量 */
    studentCount: number;
    /** 课程数量 */
    courseCount: number;
    /** 分类数量 */
    categoryCount: number;
    /** 模板数量 */
    templateCount: number;
    /** 实例数量 */
    instanceCount: number;
  };
  /** 失败的数据统计 */
  failed: {
    /** 学生数量 */
    studentCount: number;
    /** 课程数量 */
    courseCount: number;
    /** 分类数量 */
    categoryCount: number;
    /** 模板数量 */
    templateCount: number;
    /** 实例数量 */
    instanceCount: number;
  };
  /** 错误信息列表 */
  errors: string[];
  /** 警告信息列表 */
  warnings: string[];
}

/**
 * 导入选项接口
 */
export interface IImportOptions {
  /** 是否覆盖已存在的数据 */
  overwrite: boolean;
  /** 是否跳过无效数据 */
  skipInvalid: boolean;
  /** 是否创建备份 */
  createBackup: boolean;
  /** 导入模式 */
  mode: 'merge' | 'replace' | 'append';
  /** 要导入的数据类型 */
  dataTypes?: Array<'students' | 'courses' | 'courseCategories' | 'scheduleTemplates' | 'scheduleInstances' | 'settings'>;
}

/**
 * 导出选项接口
 */
export interface IExportOptions {
  /** 导出格式 */
  format: 'json' | 'csv';
  /** 是否压缩 */
  compress: boolean;
  /** 是否包含设置 */
  includeSettings: boolean;
  /** 要导出的数据类型 */
  dataTypes?: Array<'students' | 'courses' | 'courseCategories' | 'scheduleTemplates' | 'scheduleInstances' | 'settings'>;
  /** 筛选条件 */
  filters?: {
    /** 学生ID列表 */
    studentIds?: string[];
    /** 课程ID列表 */
    courseIds?: string[];
    /** 分类ID列表 */
    categoryIds?: string[];
    /** 日期范围 */
    dateRange?: {
      startDate: string;
      endDate: string;
    };
  };
}

/**
 * 数据导入导出服务类
 * @description 负责系统数据的导入导出功能
 */
export class DataImportExportService {
  /**
   * 导出所有数据
   * @param options 导出选项
   * @returns 导出结果
   */
  async exportData(options: Partial<IExportOptions> = {}): Promise<OperationResult<string>> {
    try {
      const defaultOptions: IExportOptions = {
        format: 'json',
        compress: false,
        includeSettings: true,
        dataTypes: ['students', 'courses', 'courseCategories', 'scheduleTemplates', 'scheduleInstances', 'settings'],
        ...options
      };

      // 收集数据
      const exportData: IExportData = {
        version: DATA_VERSION.CURRENT,
        timestamp: Date.now(),
        description: `数据导出 - ${new Date().toLocaleString()}`,
        data: {
          students: [],
          courses: [],
          courseCategories: [],
          scheduleTemplates: [],
          scheduleInstances: [],
          appSettings: {},
          userPreferences: {}
        },
        statistics: {
          studentCount: 0,
          courseCount: 0,
          categoryCount: 0,
          templateCount: 0,
          instanceCount: 0
        }
      };

      // 导出学生数据
      if (defaultOptions.dataTypes!.includes('students')) {
        const studentsResult = await studentService.getAllStudents();
        if (studentsResult.success) {
          let students = studentsResult.data;
          
          // 应用筛选条件
          if (defaultOptions.filters?.studentIds) {
            students = students.filter(s => defaultOptions.filters!.studentIds!.includes(s.id));
          }
          
          exportData.data.students = students;
          exportData.statistics.studentCount = students.length;
        }
      }

      // 导出课程数据
      if (defaultOptions.dataTypes!.includes('courses')) {
        const coursesResult = await courseService.getAllCourses();
        if (coursesResult.success) {
          let courses = coursesResult.data;
          
          // 应用筛选条件
          if (defaultOptions.filters?.courseIds) {
            courses = courses.filter(c => defaultOptions.filters!.courseIds!.includes(c.id));
          }
          
          exportData.data.courses = courses;
          exportData.statistics.courseCount = courses.length;
        }
      }

      // 导出课程分类数据
      if (defaultOptions.dataTypes!.includes('courseCategories')) {
        const categoriesResult = await courseCategoryService.getAllCategories();
        if (categoriesResult.success) {
          let categories = categoriesResult.data;
          
          // 应用筛选条件
          if (defaultOptions.filters?.categoryIds) {
            categories = categories.filter(c => defaultOptions.filters!.categoryIds!.includes(c.id));
          }
          
          exportData.data.courseCategories = categories;
          exportData.statistics.categoryCount = categories.length;
        }
      }

      // 导出课程安排模板数据
      if (defaultOptions.dataTypes!.includes('scheduleTemplates')) {
        const templatesResult = await scheduleService.getAllTemplates();
        if (templatesResult.success) {
          let templates = templatesResult.data;
          
          // 应用筛选条件
          if (defaultOptions.filters?.studentIds) {
            templates = templates.filter(t => defaultOptions.filters!.studentIds!.includes(t.studentId));
          }
          
          if (defaultOptions.filters?.courseIds) {
            templates = templates.filter(t => defaultOptions.filters!.courseIds!.includes(t.courseId));
          }
          
          if (defaultOptions.filters?.dateRange) {
            const { startDate, endDate } = defaultOptions.filters.dateRange;
            templates = templates.filter(t => 
              t.startDate >= startDate && (t.endDate || t.startDate) <= endDate
            );
          }
          
          exportData.data.scheduleTemplates = templates;
          exportData.statistics.templateCount = templates.length;
        }
      }

      // 导出课程实例数据
      if (defaultOptions.dataTypes!.includes('scheduleInstances')) {
        const instancesResult = await scheduleService.getAllInstances();
        if (instancesResult.success) {
          let instances = instancesResult.data;
          
          // 应用筛选条件
          if (defaultOptions.filters?.studentIds) {
            instances = instances.filter(i => defaultOptions.filters!.studentIds!.includes(i.studentId));
          }
          
          if (defaultOptions.filters?.courseIds) {
            instances = instances.filter(i => defaultOptions.filters!.courseIds!.includes(i.courseId));
          }
          
          if (defaultOptions.filters?.dateRange) {
            const { startDate, endDate } = defaultOptions.filters.dateRange;
            instances = instances.filter(i => i.date >= startDate && i.date <= endDate);
          }
          
          exportData.data.scheduleInstances = instances;
          exportData.statistics.instanceCount = instances.length;
        }
      }

      // 导出设置数据
      if (defaultOptions.dataTypes!.includes('settings') && defaultOptions.includeSettings) {
        const appSettingsResult = await storageService.getItem(STORAGE_KEYS.APP_SETTINGS);
        if (appSettingsResult.success) {
          exportData.data.appSettings = (appSettingsResult.data as Record<string, unknown>) || {};
        }

        const userPreferencesResult = await storageService.getItem(STORAGE_KEYS.USER_PREFERENCES);
        if (userPreferencesResult.success) {
          exportData.data.userPreferences = (userPreferencesResult.data as Record<string, unknown>) || {};
        }
      }

      // 生成导出内容
      let exportContent: string;
      
      if (defaultOptions.format === 'json') {
        exportContent = JSON.stringify(exportData, null, 2);
      } else if (defaultOptions.format === 'csv') {
        exportContent = this.convertToCSV(exportData);
      } else {
        return {
          success: false,
          error: '不支持的导出格式'
        };
      }

      // 压缩处理
      if (defaultOptions.compress) {
        exportContent = this.compressData(exportContent);
      }

      return {
        success: true,
        data: exportContent
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '导出数据失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 导入数据
   * @param importContent 导入内容
   * @param options 导入选项
   * @returns 导入结果
   */
  async importData(importContent: string, options: Partial<IImportOptions> = {}): Promise<OperationResult<IImportResult>> {
    try {
      const defaultOptions: IImportOptions = {
        overwrite: false,
        skipInvalid: true,
        createBackup: true,
        mode: 'merge',
        dataTypes: ['students', 'courses', 'courseCategories', 'scheduleTemplates', 'scheduleInstances', 'settings'],
        ...options
      };

      // 创建备份
      if (defaultOptions.createBackup) {
        await storageService.createBackup('导入前自动备份');
      }

      // 解析导入数据
      let importData: IExportData;
      try {
        // 检查是否为压缩数据
        const decompressedContent = this.isCompressed(importContent) 
          ? this.decompressData(importContent) 
          : importContent;
        
        importData = JSON.parse(decompressedContent);
      } catch (parseError) {
        return {
          success: false,
          error: '导入数据格式错误，请检查文件内容'
        };
      }

      // 验证数据格式
      const validationResult = this.validateImportData(importData);
      if (!validationResult.success) {
        return validationResult;
      }

      // 初始化导入结果
      const importResult: IImportResult = {
        success: true,
        imported: {
          studentCount: 0,
          courseCount: 0,
          categoryCount: 0,
          templateCount: 0,
          instanceCount: 0
        },
        skipped: {
          studentCount: 0,
          courseCount: 0,
          categoryCount: 0,
          templateCount: 0,
          instanceCount: 0
        },
        failed: {
          studentCount: 0,
          courseCount: 0,
          categoryCount: 0,
          templateCount: 0,
          instanceCount: 0
        },
        errors: [],
        warnings: []
      };

      // 导入课程分类（优先导入，因为课程依赖分类）
      if (defaultOptions.dataTypes!.includes('courseCategories') && importData.data.courseCategories) {
        const categoryResult = await this.importCourseCategories(
          importData.data.courseCategories, 
          defaultOptions
        );
        importResult.imported.categoryCount = categoryResult.imported;
        importResult.skipped.categoryCount = categoryResult.skipped;
        importResult.failed.categoryCount = categoryResult.failed;
        importResult.errors.push(...categoryResult.errors);
        importResult.warnings.push(...categoryResult.warnings);
      }

      // 导入学生数据
      if (defaultOptions.dataTypes!.includes('students') && importData.data.students) {
        const studentResult = await this.importStudents(importData.data.students, defaultOptions);
        importResult.imported.studentCount = studentResult.imported;
        importResult.skipped.studentCount = studentResult.skipped;
        importResult.failed.studentCount = studentResult.failed;
        importResult.errors.push(...studentResult.errors);
        importResult.warnings.push(...studentResult.warnings);
      }

      // 导入课程数据
      if (defaultOptions.dataTypes!.includes('courses') && importData.data.courses) {
        const courseResult = await this.importCourses(importData.data.courses, defaultOptions);
        importResult.imported.courseCount = courseResult.imported;
        importResult.skipped.courseCount = courseResult.skipped;
        importResult.failed.courseCount = courseResult.failed;
        importResult.errors.push(...courseResult.errors);
        importResult.warnings.push(...courseResult.warnings);
      }

      // 导入课程安排模板
      if (defaultOptions.dataTypes!.includes('scheduleTemplates') && importData.data.scheduleTemplates) {
        const templateResult = await this.importScheduleTemplates(
          importData.data.scheduleTemplates, 
          defaultOptions
        );
        importResult.imported.templateCount = templateResult.imported;
        importResult.skipped.templateCount = templateResult.skipped;
        importResult.failed.templateCount = templateResult.failed;
        importResult.errors.push(...templateResult.errors);
        importResult.warnings.push(...templateResult.warnings);
      }

      // 导入课程实例
      if (defaultOptions.dataTypes!.includes('scheduleInstances') && importData.data.scheduleInstances) {
        const instanceResult = await this.importScheduleInstances(
          importData.data.scheduleInstances, 
          defaultOptions
        );
        importResult.imported.instanceCount = instanceResult.imported;
        importResult.skipped.instanceCount = instanceResult.skipped;
        importResult.failed.instanceCount = instanceResult.failed;
        importResult.errors.push(...instanceResult.errors);
        importResult.warnings.push(...instanceResult.warnings);
      }

      // 导入设置数据
      if (defaultOptions.dataTypes!.includes('settings')) {
        if (importData.data.appSettings) {
          await storageService.setItem(STORAGE_KEYS.APP_SETTINGS, importData.data.appSettings);
        }
        
        if (importData.data.userPreferences) {
          await storageService.setItem(STORAGE_KEYS.USER_PREFERENCES, importData.data.userPreferences);
        }
      }

      // 检查是否有错误
      const totalErrors = importResult.errors.length;
      const totalFailed = Object.values(importResult.failed).reduce((sum, count) => sum + count, 0);
      
      if (totalErrors > 0 || totalFailed > 0) {
        importResult.success = false;
      }

      return {
        success: true,
        data: importResult
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '导入数据失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 验证导入数据格式
   * @param importData 导入数据
   * @returns 验证结果
   */
  private validateImportData(importData: unknown): OperationResult<void> {
    if (!importData || typeof importData !== 'object') {
      return {
        success: false,
        error: '导入数据格式无效'
      };
    }

    const data = importData as any;

    if (!data.version) {
      return {
        success: false,
        error: '导入数据缺少版本信息'
      };
    }

    if (!data.data || typeof data.data !== 'object') {
      return {
        success: false,
        error: '导入数据缺少数据内容'
      };
    }

    // 检查版本兼容性
    if (!this.isVersionCompatible(data.version)) {
      return {
        success: false,
        error: `数据版本不兼容：${data.version}，当前支持版本：${DATA_VERSION.CURRENT}`
      };
    }

    return {
      success: true,
      data: undefined
    };
  }

  /**
   * 导入学生数据
   * @param students 学生数据
   * @param options 导入选项
   * @returns 导入结果
   */
  private async importStudents(
    students: IStudent[], 
    options: IImportOptions
  ): Promise<{ imported: number; skipped: number; failed: number; errors: string[]; warnings: string[] }> {
    let imported = 0;
    let skipped = 0;
    let failed = 0;
    const errors: string[] = [];
    const warnings: string[] = [];

    for (const student of students) {
      try {
        // 检查学生是否已存在
        const existingResult = await studentService.getStudentByStudentId(student.studentId);
        
        if (existingResult.success) {
          if (options.overwrite) {
            // 更新现有学生
            const updateResult = await studentService.updateStudent(existingResult.data.id, student);
            if (updateResult.success) {
              imported++;
            } else {
              failed++;
              errors.push(`更新学生失败 ${student.name}: ${updateResult.error}`);
            }
          } else {
            skipped++;
            warnings.push(`学生已存在，跳过：${student.name} (${student.studentId})`);
          }
        } else {
          // 创建新学生
          const createResult = await studentService.createStudent(student);
          if (createResult.success) {
            imported++;
          } else {
            if (options.skipInvalid) {
              skipped++;
              warnings.push(`跳过无效学生：${student.name} - ${createResult.error}`);
            } else {
              failed++;
              errors.push(`创建学生失败 ${student.name}: ${createResult.error}`);
            }
          }
        }
      } catch (error) {
        failed++;
        const errorMessage = error instanceof Error ? error.message : '未知错误';
        errors.push(`处理学生失败 ${student.name}: ${errorMessage}`);
      }
    }

    return { imported, skipped, failed, errors, warnings };
  }

  /**
   * 导入课程分类数据
   * @param categories 分类数据
   * @param options 导入选项
   * @returns 导入结果
   */
  private async importCourseCategories(
    categories: ICourseCategory[], 
    options: IImportOptions
  ): Promise<{ imported: number; skipped: number; failed: number; errors: string[]; warnings: string[] }> {
    let imported = 0;
    let skipped = 0;
    let failed = 0;
    const errors: string[] = [];
    const warnings: string[] = [];

    for (const category of categories) {
      try {
        // 检查分类是否已存在
        const existingResult = await courseCategoryService.getCategoryByCategoryCode(category.categoryCode);
        
        if (existingResult.success) {
          if (options.overwrite && !existingResult.data.isPreset) {
            // 更新现有分类（不更新预设分类）
            const updateResult = await courseCategoryService.updateCategory(existingResult.data.id, category);
            if (updateResult.success) {
              imported++;
            } else {
              failed++;
              errors.push(`更新分类失败 ${category.name}: ${updateResult.error}`);
            }
          } else {
            skipped++;
            warnings.push(`分类已存在，跳过：${category.name} (${category.categoryCode})`);
          }
        } else {
          // 创建新分类
          const createResult = await courseCategoryService.createCategory(category);
          if (createResult.success) {
            imported++;
          } else {
            if (options.skipInvalid) {
              skipped++;
              warnings.push(`跳过无效分类：${category.name} - ${createResult.error}`);
            } else {
              failed++;
              errors.push(`创建分类失败 ${category.name}: ${createResult.error}`);
            }
          }
        }
      } catch (error) {
        failed++;
        const errorMessage = error instanceof Error ? error.message : '未知错误';
        errors.push(`处理分类失败 ${category.name}: ${errorMessage}`);
      }
    }

    return { imported, skipped, failed, errors, warnings };
  }

  /**
   * 导入课程数据
   * @param courses 课程数据
   * @param options 导入选项
   * @returns 导入结果
   */
  private async importCourses(
    courses: ICourse[], 
    options: IImportOptions
  ): Promise<{ imported: number; skipped: number; failed: number; errors: string[]; warnings: string[] }> {
    let imported = 0;
    let skipped = 0;
    let failed = 0;
    const errors: string[] = [];
    const warnings: string[] = [];

    for (const course of courses) {
      try {
        // 检查课程是否已存在
        const existingResult = await courseService.getCourseByCourseCode(course.courseCode);
        
        if (existingResult.success) {
          if (options.overwrite) {
            // 更新现有课程
            const updateResult = await courseService.updateCourse(existingResult.data.id, course);
            if (updateResult.success) {
              imported++;
            } else {
              failed++;
              errors.push(`更新课程失败 ${course.name}: ${updateResult.error}`);
            }
          } else {
            skipped++;
            warnings.push(`课程已存在，跳过：${course.name} (${course.courseCode})`);
          }
        } else {
          // 创建新课程
          const createResult = await courseService.createCourse(course);
          if (createResult.success) {
            imported++;
          } else {
            if (options.skipInvalid) {
              skipped++;
              warnings.push(`跳过无效课程：${course.name} - ${createResult.error}`);
            } else {
              failed++;
              errors.push(`创建课程失败 ${course.name}: ${createResult.error}`);
            }
          }
        }
      } catch (error) {
        failed++;
        const errorMessage = error instanceof Error ? error.message : '未知错误';
        errors.push(`处理课程失败 ${course.name}: ${errorMessage}`);
      }
    }

    return { imported, skipped, failed, errors, warnings };
  }

  /**
   * 导入课程安排模板数据
   * @param templates 模板数据
   * @param options 导入选项
   * @returns 导入结果
   */
  private async importScheduleTemplates(
    templates: IScheduleTemplate[], 
    options: IImportOptions
  ): Promise<{ imported: number; skipped: number; failed: number; errors: string[]; warnings: string[] }> {
    let imported = 0;
    let skipped = 0;
    let failed = 0;
    const errors: string[] = [];
    const warnings: string[] = [];

    for (const template of templates) {
      try {
        // 检查模板是否已存在（通过ID）
        const existingResult = await scheduleService.getTemplateById(template.id);
        
        if (existingResult.success) {
          if (options.overwrite) {
            // 更新现有模板
            const updateResult = await scheduleService.updateTemplate(template.id, template);
            if (updateResult.success) {
              imported++;
            } else {
              failed++;
              errors.push(`更新模板失败 ${template.id}: ${updateResult.error}`);
            }
          } else {
            skipped++;
            warnings.push(`模板已存在，跳过：${template.id}`);
          }
        } else {
          // 创建新模板
          const createResult = await scheduleService.createTemplate(template);
          if (createResult.success) {
            imported++;
          } else {
            if (options.skipInvalid) {
              skipped++;
              warnings.push(`跳过无效模板：${template.id} - ${createResult.error}`);
            } else {
              failed++;
              errors.push(`创建模板失败 ${template.id}: ${createResult.error}`);
            }
          }
        }
      } catch (error) {
        failed++;
        const errorMessage = error instanceof Error ? error.message : '未知错误';
        errors.push(`处理模板失败 ${template.id}: ${errorMessage}`);
      }
    }

    return { imported, skipped, failed, errors, warnings };
  }

  /**
   * 导入课程实例数据
   * @param instances 实例数据
   * @param options 导入选项
   * @returns 导入结果
   */
  private async importScheduleInstances(
    instances: IScheduleInstance[], 
    options: IImportOptions
  ): Promise<{ imported: number; skipped: number; failed: number; errors: string[]; warnings: string[] }> {
    let imported = 0;
    let skipped = 0;
    let failed = 0;
    const errors: string[] = [];
    const warnings: string[] = [];

    for (const instance of instances) {
      try {
        // 检查实例是否已存在（通过ID）
        const existingResult = await scheduleService.getInstanceById(instance.id);
        
        if (existingResult.success) {
          if (options.overwrite) {
            // 更新现有实例
            const updateResult = await scheduleService.updateInstance(instance.id, instance);
            if (updateResult.success) {
              imported++;
            } else {
              failed++;
              errors.push(`更新实例失败 ${instance.id}: ${updateResult.error}`);
            }
          } else {
            skipped++;
            warnings.push(`实例已存在，跳过：${instance.id}`);
          }
        } else {
          // 由于实例通常由模板自动生成，这里跳过创建
          skipped++;
          warnings.push(`实例将由模板自动生成，跳过：${instance.id}`);
        }
      } catch (error) {
        failed++;
        const errorMessage = error instanceof Error ? error.message : '未知错误';
        errors.push(`处理实例失败 ${instance.id}: ${errorMessage}`);
      }
    }

    return { imported, skipped, failed, errors, warnings };
  }

  /**
   * 转换为CSV格式
   * @param exportData 导出数据
   * @returns CSV字符串
   */
  private convertToCSV(exportData: IExportData): string {
    const csvSections: string[] = [];

    // 学生数据CSV
    if (exportData.data.students.length > 0) {
      csvSections.push('=== 学生数据 ===');
      const studentHeaders = ['ID', '姓名', '学号', '年级', '班级', '电话', '状态', '创建时间'];
      csvSections.push(studentHeaders.join(','));
      
      exportData.data.students.forEach(student => {
        const row = [
          student.id,
          student.name,
          student.studentId,
          student.grade || '',
          student.class || '',
          student.phone || '',
          student.status.toString(),
          new Date(student.createdAt).toLocaleString()
        ];
        csvSections.push(row.join(','));
      });
      csvSections.push('');
    }

    // 课程数据CSV
    if (exportData.data.courses.length > 0) {
      csvSections.push('=== 课程数据 ===');
      const courseHeaders = ['ID', '课程名称', '课程代码', '教师', '颜色', '状态', '创建时间'];
      csvSections.push(courseHeaders.join(','));
      
      exportData.data.courses.forEach(course => {
        const row = [
          course.id,
          course.name,
          course.courseCode,
          course.teacher,
          course.color,
          course.status.toString(),
          new Date(course.createdAt).toLocaleString()
        ];
        csvSections.push(row.join(','));
      });
      csvSections.push('');
    }

    return csvSections.join('\n');
  }

  /**
   * 检查版本兼容性
   * @param version 数据版本
   * @returns 是否兼容
   */
  private isVersionCompatible(version: string): boolean {
    // 简单的版本兼容性检查
    return version === DATA_VERSION.CURRENT || version >= DATA_VERSION.MIN_SUPPORTED;
  }

  /**
   * 压缩数据
   * @param data 原始数据
   * @returns 压缩后的数据
   */
  private compressData(data: string): string {
    // 简单的压缩标记，实际项目中可以使用更复杂的压缩算法
    return `__COMPRESSED__${btoa(data)}`;
  }

  /**
   * 解压数据
   * @param data 压缩后的数据
   * @returns 原始数据
   */
  private decompressData(data: string): string {
    if (this.isCompressed(data)) {
      return atob(data.replace('__COMPRESSED__', ''));
    }
    return data;
  }

  /**
   * 检查数据是否被压缩
   * @param data 数据
   * @returns 是否被压缩
   */
  private isCompressed(data: string): boolean {
    return data.startsWith('__COMPRESSED__');
  }

  /**
   * 清除所有数据
   * @description 清除所有存储的数据，包括学生、课程、课表等
   * @returns 操作结果
   */
  async clearData(): Promise<OperationResult<void>> {
    try {
      // 清除所有存储的数据
      await Promise.all([
        storageService.removeItem(STORAGE_KEYS.STUDENTS),
        storageService.removeItem(STORAGE_KEYS.COURSES),
        storageService.removeItem(STORAGE_KEYS.COURSE_CATEGORIES),
        storageService.removeItem(STORAGE_KEYS.SCHEDULE_TEMPLATES),
        storageService.removeItem(STORAGE_KEYS.SCHEDULE_INSTANCES),
        storageService.removeItem(STORAGE_KEYS.APP_SETTINGS),
        storageService.removeItem(STORAGE_KEYS.USER_PREFERENCES)
      ]);

      return {
        success: true,
        data: undefined
      };
    } catch (error) {
      console.error('清除数据失败:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : '清除数据失败'
      };
    }
  }

  /**
   * 获取数据统计信息
   * @description 获取当前存储的各类数据的统计信息
   * @returns 统计信息
   */
  async getStatistics(): Promise<OperationResult<{
    students: number;
    courses: number;
    courseCategories: number;
    scheduleTemplates: number;
    scheduleInstances: number;
    totalSize: number;
    lastUpdated: number;
  }>> {
    try {
      // 获取各类数据
      const [
        studentsResult,
        coursesResult,
        categoriesResult,
        templatesResult,
        instancesResult
      ] = await Promise.all([
        studentService.getAllStudents(),
        courseService.getAllCourses(),
        courseCategoryService.getAllCategories(),
        scheduleService.getAllTemplates(),
        scheduleService.getAllInstances()
      ]);

      // 计算统计信息
      const students = studentsResult.success ? studentsResult.data.length : 0;
      const courses = coursesResult.success ? coursesResult.data.length : 0;
      const courseCategories = categoriesResult.success ? categoriesResult.data.length : 0;
      const scheduleTemplates = templatesResult.success ? templatesResult.data.length : 0;
      const scheduleInstances = instancesResult.success ? instancesResult.data.length : 0;

      // 估算总大小（简单计算）
      const totalSize = (students + courses + courseCategories + scheduleTemplates + scheduleInstances) * 1024; // 假设每条记录约1KB

      return {
        success: true,
        data: {
          students,
          courses,
          courseCategories,
          scheduleTemplates,
          scheduleInstances,
          totalSize,
          lastUpdated: Date.now()
        }
      };
    } catch (error) {
      console.error('获取统计信息失败:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : '获取统计信息失败'
      };
    }
  }
}

/**
 * 默认数据导入导出服务实例
 */
export const dataImportExportService = new DataImportExportService();